﻿@model NavigatorBarModel
@{
    Layout = "_Default";
    ViewData["Title"] = "Group";
}
@section css {
    <link href="~/node_modules/nestable2/dist/jquery.nestable.min.css" rel="stylesheet" />
    <link href="~/css/site.css" rel="stylesheet" />

}
@section javascript {
    <script>
        $(function () {
            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();
            $('.dd').nestable('serialize');
            $('#btn_query').on('click', function () {
                $("#TableGroup").bootstrapTable('refresh');
            });

            $('#btn_repeat').on('click', function () {
                $("#txt_group_name").val("");
                $("#TableGroup").bootstrapTable('refresh');
            });

            $('.btn_add').on('click', function () {
                edittype = true;
                $('#myModalLabel').html('角色添加窗口');
                $('#ID').val(0);
                $('#Geoupname').val('');
                $('#explain').val('');
                $('#dialogNew').modal();
            });

            $('#btnSubmit').click(function () {
                var requesturl = '/api/Group/add';
                if (!edittype)
                    requesturl = '/api/Group/edit';
                $.ajax({
                    type: 'put',
                    url: requesturl,
                    contentType: 'application/json',
                    data: JSON.stringify({ "id": parseInt($('#ID').val()), "name": $('#Geoupname').val(), "explain": $('#explain').val() }),
                    datatype: 'json',
                    success: function (res) {
                        $('#dialogNew').modal('hide');
                        if (res.state == 200) {
                            $("#TableGroup").bootstrapTable('refresh');
                            toastr.success(res.message);
                        }
                        else {
                            toastr.error(res.message);
                        }
                    },
                    error: function (e) {
                        toastr.error(e.responseText);
                    }
                });
            });

            $('.btn_delete').on('click', function () {
                var data = $("#TableGroup").bootstrapTable('getSelections');
                if (data.length > 0) {
                    deleteRow(data);
                } else {
                    toastr.error("请选中后操作！");
                }
            });

            $('.tb_edit').click(function () {
                var data = $("#TableGroup").bootstrapTable('getSelections');
                if (data.length == 1) {
                    if (data[0] != null && data[0].id != 0)
                        edit(data[0].id);
                    else console.log(data[0].id);
                } else {
                    toastr.error("请选中一行后编辑！");
                }
            });

            $('.tb_assignRole').click(function () {
                var data = $("#TableGroup").bootstrapTable('getSelections');
                if (data.length == 1) {
                    if (data[0] != null && data[0].id != 0) {
                        $.ajax({
                            url: '/api/Navigator/detail',
                            type: "get",
                            data: data[0],
                            contentType: 'application/json',
                            success: function (res) {
                                if (res.state == 200) {
                                    var menus = $nestMenu.find('input:checkbox');
                                    menus.prop('checked', false);
                                    var Itemlist = res.data;
                                    //console.error(Itemlist);
                                    $.each(Itemlist, function (index, item) {
                                        //console.log(item.menuid);
                                        // var selector = $.format('[value={0}]', item.menuid);
                                        //console.log(item.menuid);
                                        //console.log(menus.filter('[value=' + item.menuid + ']'));
                                        //menus.filter('[value=' + item.menuid + ']').prop('checked', true);
                                        //console.log($('input[value=' + item.menuid + ']'));
                                        $('input[value=' + item.menuid + ']').prop('checked', true);
                                    });
                                    $('#dialogMenu').modal();
                                }
                                else {
                                    toastr.error(res.message);
                                }
                            },
                            error: function (e) {
                                toastr.error(e.responseText);
                            }
                        });
                    }
                    else console.log(data[0].id);
                } else {
                    toastr.error("请选中一行后编辑！");
                }
            });

            var $nestMenu = $('#nestable_menu');
            var $nestMenuInput = $nestMenu.find('div.dd3-content');
            $nestMenuInput = $nestMenu.find('div.dd3-content');
            $nestMenuInput.on('click', ':checkbox', function () {
                var val = $(this).prop('checked');
                var child = $(this).parents('.dd3-content').next();
                if (child.hasClass('dd-list')) {
                    child.find(':checkbox').prop('checked', val);
                }
                // 子节点全部取消时父级菜单也取消
                $(this).parents('ol.dd-list').each(function (index, p) {
                    if (val === false) {
                        val = $(p).prev().next().find(':checked').length > 0;
                    }
                    $(p).prev().find(':checkbox').prop('checked', val);
                });
            }).children('.radio').hide();

            //权限
            $('#btnMenuParent').click(function () {
                var data = $("#TableGroup").bootstrapTable('getSelections');
                var menus = $nestMenu.find('input:checkbox');
                var menuObj = [];
                var i = 0;
                $.each(menus, function (index, item) {
                    if ($(item).is(':checked')) {
                        var id = parseInt($(item).attr("value"));
                        var gropu = parseInt($(item).attr("group"));
                        if (id != 0) {/*&& gropu != 1*/
                            menuObj[i] = { "id": id };
                            i++;
                        }
                    }
                });
                $.ajax({
                    url: '/api/Navigator/add?id=' + data[0].id,
                    type: "post",
                    data: JSON.stringify(menuObj),
                    contentType: 'application/json',
                    success: function (res) {
                        if (res.state == 200) {
                            toastr.success(res.message);
                            $("#TableGroup").bootstrapTable('refresh');
                        }
                        else {
                            toastr.error(res.message);
                        }
                    },
                    error: function (e) {
                        toastr.error(e.responseText);
                    }
                });
                console.log(menuObj);
            });
        });

        var edittype = true;
        var TableArrar = new Array();

        function edit(index) {
            edittype = false;
            var Info = TableArrar[index]
            if (Info != null) {
                $('#myModalLabel').html('角色编辑窗口');
                $('#Geoupname').val(Info.name);
                $('#explain').val(Info.explain);
                $('#ID').val(Info.id);
                $('#dialogNew').modal();
            }
        }

        function deleteRow(data) {
            bootbox.confirm({
                message: "确认删除吗？",
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn-primary'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            url: '/api/Group',
                            type: "delete",
                            data: JSON.stringify(data),
                            contentType: 'application/json',
                            success: function (res) {
                                if (res.state == 200) {
                                    $("#TableGroup").bootstrapTable('refresh');
                                    toastr.success(res.message);
                                }
                                else {
                                    $("#TableGroup").bootstrapTable('refresh');
                                    toastr.error(res.message);
                                }
                            },
                            error: function (e) {
                                toastr.error(e.responseText);
                            }
                        });
                    }
                }
            });
        }

        function deleteTool(id) {
            deleteRow([{ "id": id }]);
        }

        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#TableGroup').bootstrapTable({
                    url: '/api/Group',                  //请求后台的URL（*）
                    method: 'get',                      //请求方式（*）
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    sortable: false,                     //是否启用排序
                    sortOrder: "asc",                   //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                       //初始化加载第一页，默认第一页
                    pageSize: 10,                       //每页的记录行数（*）
                    pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                    search: false,                       //是否显示表格搜索，此搜索是客户端搜索，
                    strictSearch: true,
                    showColumns: true,                  //是否显示所有的列
                    showRefresh: true,                  //是否显示刷新按钮
                    minimumCountColumns: 2,             //最少允许的列数
                    clickToSelect: true,                //是否启用点击选中行
                    /*    height: 500,            */            //行高，如果没有设置height属性，表格自动根据记录条数决定表格高度
                    uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                    showToggle: true,                    //是否显示详细视图和列表视图的切换按钮
                    cardView: false,                    //是否显示详细视图
                    detailView: false,
                    columns: [
                        {
                            checkbox: true
                        }, {
                            field: 'name',
                            title: '权限组名称',
                            align: 'center'
                        }, {
                            field: 'explain',
                            title: '权限组描述',
                            align: 'center'
                        },
                        {
                            field: "agvId", title: "操作", width: 200, align: "center", formatter: function (value, row, index) {
                                TableArrar[row.id] = row;
                                var strHtml = '<button type="button" class="btn btn-primary btn-xs" onclick="edit(' + row.id + ')">编辑</button>&nbsp;' +
                                    '<button type="button" class="btn btn-danger btn-xs" onclick="deleteTool(' + row.id + ')">删除</button>';
                                return strHtml;
                            },
                            edit: false
                        }]
                });
            };
            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {                 //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit,   //页面大小
                    offset: params.offset,  //页码
                    Name: $("#txt_group_name").val()
                };
                return temp;
            };
            return oTableInit;
        };
    </script>
}

<div class="card">
    <div class="card-header">查询条件</div>
    <div class="card-body">
        <form class="form-inline">
            <div class="row">
                <div class="form-group col-sm-6 col-lg-auto">
                    <label class="control-label" for="txt_menus_name">角色名称</label>
                    <input type="text" class="form-control" id="txt_group_name">
                </div>
                <div class="form-group col-sm-6 col-lg-auto flex-sm-fill justify-content-sm-end align-self-sm-end">
                    <button style="margin:3px" type="button" id="btn_query" class="btn btn-primary btn-fill"><i class="fa fa-search" aria-hidden="true"></i><span>查询</span></button>
                    <button style="margin:3px" type="button" id="btn_repeat" class="btn btn-primary btn-fill"><i class="fa fa-repeat" aria-hidden="true"></i><span>重置</span></button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="card">
    <div class="card-header">
        查询结果
    </div>
    <div class="card-body">
        <div class="alert alert-warning" role="alert">
            <span>请谨慎修改</span>
        </div>
        <div id="toolbar" class="">
            <div class="toolbar btn-group">
                <button type="button" class="btn btn-info btn_add"><i class="fa fa-plus" aria-hidden="true"></i><span>新增</span></button>
                <button type="button" class="btn btn-primary tb_edit"><i class="fa fa-pencil" aria-hidden="true"></i><span>编辑</span></button>
                <button type="button" class="btn btn-danger btn_delete"><i class="fa fa-remove" aria-hidden="true"></i><span>删除</span></button>
                <button type="button" class="btn btn-info tb_assignRole">
                    <i class="fa fa-sitemap" aria-hidden="true"></i><span>权限</span>
                </button>
            </div>
        </div>
        <table id="TableGroup"></table>
        <div class="clearfix"></div>
    </div>
</div>
@section modal {
    <div class="modal-header">
        <h5 class="modal-title" id="myModalLabel">权限组编辑窗口</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <form class="form-inline" id="dataForm">
            <div class="form-row">
                <input type="hidden" id="ID" />
                <div class="form-group col-12">
                    <label class="control-label" for="url">权限组名称</label>
                    <input type="text" class="form-control flex-sm-fill" id="Geoupname" placeholder="不可为空，50字以内" maxlength="50" data-valid="true" />
                </div>
                <div class="form-group col-12">
                    <label class="control-label" for="url">权限组描述</label>
                    <input type="text" class="form-control flex-sm-fill" id="explain" placeholder="可为空" />
                </div>
            </div>
        </form>
    </div>
}
@section customModal{
    <div class="modal" id="dialogMenu" tabindex="-1" role="dialog" data-backdrop="static" aria-labelledby="myMenuModalLabel" aria-hidden="true">
        <div id="dialogSubMenu" class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="myMenuModalLabel">请选择菜单</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>
                <div class="modal-body modal-body-fixed">
                    <div class="dd" id="nestable_menu">
                        <ol class="dd-list">
                            @foreach (var itemMenu in Model.NavigatorMenuList)
                            {
                                <li class="dd-item dd3-item" data-id="53" data-order="150" data-category="0">
                                    @*<button class="dd-collapse" data-action="collapse" type="button">Collapse</button>
                                        <button class="dd-expand" data-action="expand" type="button">Expand</button>*@
                                    <div class="dd-handle dd3-handle"></div>
                                    <div class="dd3-content">
                                        <div class="checkbox">
                                            <label><input type="checkbox" value="@itemMenu.FatherItem.id" group="@(itemMenu.sonMenuItem.Any() ? 1:0)"><span><i class="@itemMenu.FatherItem.icon"></i>@itemMenu.FatherItem.name</span></label>
                                        </div>
                                        <span class="menuType">系统菜单</span><span class="menuOrder">@itemMenu.FatherItem.id</span>
                                    </div>
                                    @if (itemMenu.sonMenuItem.Any())
                                    {
                                        <ol class="dd-list">
                                            @foreach (var Sonitem in itemMenu.sonMenuItem)
                                            {
                                                <li class="dd-item dd3-item" data-id="54" data-order="10" data-category="0">
                                                    <div class="dd-handle dd3-handle"></div>
                                                    <div class="dd3-content">
                                                        <div class="checkbox">
                                                            <label>
                                                                <input type="checkbox" value="@Sonitem.id" group="0"><span><i class="@Sonitem.icon"></i>@Sonitem.name</span>
                                                            </label>
                                                        </div>
                                                        <span class="menuType">系统菜单</span><span class="menuOrder">@Sonitem.id</span>
                                                    </div>
                                                </li>
                                            }
                                        </ol>
                                    }
                                </li>
                            }
                        </ol>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal" id="modal-close">
                        <i class="fa fa-times"></i>
                        <span>关闭</span>
                    </button>
                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="btnMenuParent">
                        <i class="fa fa-save"></i>
                        <span>确认</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
}